package com.heima.article.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

  @Autowired Configuration configuration;
  @Autowired AuthorMapper authorMapper;

  @Resource(name = "minIOFileStorageService")
  FileStorageService fileStorageService;

  @Value("${file.minio.prefix}")
  String prefix;

  @Autowired ApArticleMapper apArticleMapper;

  @Override
  public void generateArticlePage(String content, ApArticle apArticle) {
    // 准备模板
    Template template = null;
    try {
      log.info("开始生成静态页面模板");
      template = configuration.getTemplate("article.ftl");

      // 准备数据
      Map map = new HashMap<>();
      // 准备article
      map.put("article", apArticle);
      // 准作者的id
      ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
      if (apAuthor==null){
          CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"作者不存在");
      }
      Integer authorUserId = apAuthor.getUserId();//作者对于的apUserId
      map.put("authorApUserId", authorUserId);
      // 准备content
        List contentList = JSONArray.parseArray(content);
        map.put("content", contentList);//文章的内容
      // 准备模板。输出到指定位置
      StringWriter sw = new StringWriter();
      template.process(map, sw);
      // 字符输出流
      InputStream is = new ByteArrayInputStream(sw.toString().getBytes());
      // 将模板内容输出到字符输出流//        上传到minio上
      String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", is);
      // 修改文章的static_url
        apArticle.setStaticUrl(path);
        apArticleMapper.updateById(apArticle);
        log.info("静态页面生成");
    } catch (TemplateException e) {
      e.printStackTrace();
      log.info("模板引擎生成静态页面出错,原因",e.getMessage());
        CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"模板引擎生成静态页面出错");
    } catch (IOException e) {
      e.printStackTrace();
        log.info("字符输出流出现异常");
      CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"字符输出流出现异常");
      }
  }
}
